package cheme.ProcessModel.Interpreter;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import cheme.ProcessModel.IModelElement;

public interface IUpdater extends PropertyChangeListener
{
	IModelElement getToUpdate();
	void setToUpdate(IModelElement toUpdate);
	
	Interpreter getInterpreter();
	void setInterpreter(Interpreter interpreter);
	
	boolean allowPerformUpdate(PropertyChangeEvent evt);
	
	/*
	 *--------------------------------------------------------------------------
	 */
	
	public abstract class Stub implements IUpdater
	{
		protected IModelElement toUpdate = null;
		
		protected Interpreter interpreter = null;
		
		/*
		 * Ensure that the updater refers to the same model element and interpreter
		 * (non-Javadoc)
		 * @see java.lang.Object#equals(java.lang.Object)
		 */
		@Override
		public boolean equals(Object object)
		{
			return (object instanceof Stub) && (toUpdate == ((Stub)object).getToUpdate());
		}
		
		public Stub(Interpreter interpreter, IModelElement toUpdate)
		{
			setToUpdate(toUpdate);
			setInterpreter(interpreter);
		}

		public IModelElement getToUpdate()
		{
			return toUpdate;
		}

		public void setToUpdate(IModelElement toUpdate)
		{
			this.toUpdate = toUpdate;
		}
		
		public Interpreter getInterpreter()
		{
			return interpreter;
		}

		public void setInterpreter(Interpreter interpreter)
		{
			this.interpreter = interpreter;
		}

		public boolean allowPerformUpdate(PropertyChangeEvent evt)
		{
			return true;
		}
		
		public void propertyChange(PropertyChangeEvent evt)
		{
			if(allowPerformUpdate(evt))
			{
				getInterpreter().removeUpdater(this);
				getInterpreter().update(getToUpdate());
			}
		}
	}
}
